package com.yungu.swift.admin.route.operation;

import com.alibaba.dubbo.config.annotation.Reference;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.yungu.swift.admin.consts.AdminErrorEnum;
import com.yungu.swift.assets.driver.model.dto.DriverCheckDto;
import com.yungu.swift.assets.driver.model.param.AdminDriverCheckPageParam;
import com.yungu.swift.assets.driver.model.param.AdminDriverCheckPassParam;
import com.yungu.swift.assets.driver.model.param.AdminDriverCheckRejectParam;
import com.yungu.swift.assets.driver.service.DriverCheckService;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.base.model.PageVo;
import com.yungu.swift.base.model.admin.AdminBusinessParam;
import com.yungu.swift.base.model.annotation.ResponseImgOverride;
import com.yungu.swift.constants.CommonConstant;
import com.yungu.swift.utils.ParamUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import javassist.runtime.Desc;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import static com.yungu.swift.admin.config.NacosListener.SYS_CONFIG;

/**
 * @author : cuixiuyin
 * @date : 2019/7/1
 */
@Slf4j
@RestController
@RequestMapping("/admin/v1/operation/driver/check")
@Api(value = "【运营管理】", tags = "司机资质审核")
public class DriverCheckAdmin {

    private static final String REGISTER_URL = "%s/h5/driver/register?appid=%s&type=%s&agentUuid=%s&companyUuid=%s";
    private static final String TAXI_REGISTER_URL = "%s/h5/taxiDriver/register?appid=%s&type=%s&agentUuid=%s&companyUuid=%s";

    @Reference
    private DriverCheckService driverCheckService;

    @ResponseImgOverride
    @RequestMapping(value = "/queryPage", method = RequestMethod.POST)
    @ApiOperation(value = "司机资质审核分页查询", httpMethod = "POST")
    public ResponseData<PageVo<DriverCheckDto>> queryPage(@RequestBody AdminDriverCheckPageParam checkPageParam) {
        if (ParamUtil.isIllegal(checkPageParam.getStatus(), checkPageParam.getBusinessType())) {
            return ResponseData.buildErrorResponse(AdminErrorEnum.PARAM_ERROR.getCode(), AdminErrorEnum.PARAM_ERROR.getMsg());
        }
        return driverCheckService.queryPage(checkPageParam);
    }

    @ResponseImgOverride
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    @ApiOperation(value = "司机资质审核信息详情", httpMethod = "GET")
    public ResponseData<DriverCheckDto> detail(@RequestParam String uuid) {
        return driverCheckService.get(uuid);
    }


    @RequestMapping(value = "/pass", method = RequestMethod.POST)
    @ApiOperation(value = "司机资质审核通过", httpMethod = "POST")
    public ResponseData<Boolean> pass(@RequestBody AdminDriverCheckPassParam checkPassParam) {
        if (ParamUtil.isIllegal(checkPassParam.getBusinessType())) {
            return ResponseData.buildErrorResponse(AdminErrorEnum.PARAM_ERROR.getCode(), AdminErrorEnum.PARAM_ERROR.getMsg());
        }
        return driverCheckService.pass(checkPassParam);
    }

    @RequestMapping(value = "/reject", method = RequestMethod.POST)
    @ApiOperation(value = "司机资质审核驳回", httpMethod = "POST")
    public ResponseData<Boolean> reject(@RequestBody AdminDriverCheckRejectParam checkRejectParam) {
        if (ParamUtil.isIllegal(checkRejectParam.getRemark())) {
            return ResponseData.buildErrorResponse(AdminErrorEnum.PARAM_ERROR.getCode(), AdminErrorEnum.PARAM_ERROR.getMsg());
        }
        return driverCheckService.reject(checkRejectParam);
    }

    @RequestMapping(value = "/QrCode", method = RequestMethod.POST)
    @ApiOperation(value = "下载二维码", httpMethod = "POST")
    public void download(@RequestBody AdminBusinessParam businessParam, HttpServletResponse response) {
        if (ParamUtil.isIllegal(businessParam.getBusinessType())) {
            return;
        }
        String fileName = "";
        String registerUrl = String.format(REGISTER_URL, SYS_CONFIG.getApiHost(), businessParam.getAppid(),
                businessParam.getBusinessType(), businessParam.getAgentUuid(), businessParam.getCompanyUuid());
        switch (businessParam.getBusinessType()) {
            case CommonConstant.BUSINESS_TYPE_TAXI + "":
                fileName = "出租车司机注册二维码";
                registerUrl = String.format(TAXI_REGISTER_URL, SYS_CONFIG.getApiHost(), businessParam.getAppid(),
                        businessParam.getBusinessType(), businessParam.getAgentUuid(), businessParam.getCompanyUuid());
                break;
            case CommonConstant.BUSINESS_TYPE_SPEC + "":
                fileName = "专车司机注册二维码";
                break;
            case CommonConstant.BUSINESS_TYPE_POOL + "":
                fileName = "跨城拼车司机注册二维码";
                break;
            case CommonConstant.BUSINESS_TYPE_EXPRESS + "":
                fileName = "快车司机注册二维码";
                break;
            default:
                break;
        }
        try {
            Map<EncodeHintType, Object> hints = new HashMap<>(4);
            hints.put(EncodeHintType.MARGIN, 0);
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            BitMatrix bitMatrix = new QRCodeWriter().encode(registerUrl, BarcodeFormat.QR_CODE, 250, 250, hints);
            //1.去白边
            int[] rec = bitMatrix.getEnclosingRectangle();
            int resWidth = rec[2] + 1;
            int resHeight = rec[3] + 1;
            BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
            resMatrix.clear();
            for (int i = 0; i < resWidth; i++) {
                for (int j = 0; j < resHeight; j++) {
                    if (bitMatrix.get(i + rec[0], j + rec[1])) {
                        resMatrix.set(i, j);
                    }
                }
            }
            // 2
            int width = resMatrix.getWidth();
            int height = resMatrix.getHeight();
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    image.setRGB(x, y, resMatrix.get(x, y) == true ? Color.BLACK.getRGB() : Color.WHITE.getRGB());
                }
            }
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName + ".png", "UTF-8"));
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("utf-8");
            ImageIO.write(image, "png", response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
